package updown.service.jar;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import updown.config.CommonConfig;
import updown.constant.MsgConstant;
import updown.data.SseCacheData;
import updown.domain.ServiceMapDto;
import updown.service.updown.LocalService;
import updown.util.DateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title: ww.kaixin.downupservice.serviceInfo </p>
 * <p>Description:updown: - 本地 jar 包存储 serviceInfo </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/11/3
 * @Version: 1.0
 */
@Slf4j
@Service
@EnableScheduling
public class LocalFileService {

    @Autowired
    private SseCacheData sseCacheData;

    @Autowired
    private CommonConfig commonConfig;

    @Autowired
    private LocalService localService;

    /**
     * jar 包保存到本地指定位置
     *
     * @param file
     * @param serviceName
     * @param localPath
     * @param taskId
     * @return 正常则是路径地址： 已存在、IO失败，则返回 fail 字符串
     */
    public String downToLocal(MultipartFile file,String originalFileName, String serviceName, String version, String taskId) {
        log.info("downToLocal(),file{},originalFileName:{},serviceName:{},version:{},taskId:{}",file,originalFileName,serviceName,version,taskId);

        File mkdir = FileUtil.mkdir(this.commonConfig.getJarPath() + "/" + serviceName);
        log.info("上传文件的名称:{}",originalFileName);
        List<String> split = StrUtil.split(originalFileName, ".");
        String localPath = this.commonConfig.getJarPath()  + "/" + serviceName + "/" + split.get(0) + "-"  + version + "." + split.get(1);
        log.info("上传jar包，保存到本地的fileName是：{}",localPath);
        File localFile = new File(localPath);
        if (localFile.exists()){
            return MsgConstant.fail + "本地文件已存在";
        }

        try {
            FileCopyUtils.copy(file.getInputStream(),new FileOutputStream(localFile));
        } catch (IOException e) {
            log.info("FileCopyUtils 失败,报错信息:{}", e);
        }
        return localPath;
    }

    /**
     * 查看指定服务，/opt/app/yq-auth/ 下的历史jar包信息
     * @param serviceName
     * @return
     */
    public List<String> getLocalJarFileByServiceName(String serviceName) {
        File dir = new File(commonConfig.getJarPath() + "/" + serviceName);
        if (!dir.exists()){
            return new ArrayList<>();
        }
        List<String> fileNames = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files.length < 1) return new ArrayList<>();
        for (File file : files) {
            if(!file.isDirectory()){
                fileNames.add(file.toString());
            }
        }
        return fileNames;
    }

    /**
     * 查看指定服务，/opt/app/yq-auth/ 下的历史jar包信息 , 返回 file list
     * @param serviceName
     * @return
     */
    public List<File> getLocalJarFileByServiceNameReturnFile(String serviceName) {
        File dir = new File(commonConfig.getJarPath() + "/" + serviceName);
        ArrayList<File> fileList = new ArrayList<>();
        if (!dir.exists()){
            return fileList;
        }
        File[] files = dir.listFiles();
        if (files.length < 1) return fileList;
        for (File file : files) {
            fileList.add(file);
        }
        return fileList;
    }

    /**
     * 删除jar
     * @param fileLocalPath
     */
    public String deleteJarByLocalPath(String fileLocalPath) {
        File file = new File(fileLocalPath);
        if (file == null || !file.exists()){
            log.info("文件不存在");
            return "文件不存在";
        }
        file.delete();
        log.info("删除成功");
        return "success";
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void deleteJar(){
        try {
            log.info("执行jar 删除操作");
            if (commonConfig.getDeleteJarForHour() == null || commonConfig.getDeleteJarForHour() == 0){
                log.info("未配置删除Jar 的时间间隔，默认不删除");
            }else {
                List<ServiceMapDto> serviceAll = localService.getAll();
                if (serviceAll.isEmpty()){
                    log.info("没有服务不删除");
                }else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    for (ServiceMapDto service : serviceAll) {
                        List<File> files = getLocalJarFileByServiceNameReturnFile(service.getServiceName());
                        if (!files.isEmpty()){
                            for (File file : files) {
                                String lastModifyDateTime = sdf.format(file.lastModified());
                                if (DateUtils.getMinutesBetweenNoError(lastModifyDateTime,DateUtils.getCurDateTime()) >= commonConfig.getDeleteJarForHour() * 60){
                                    log.info("file:{} 超过：{} h，删除",file,commonConfig.getDeleteJarForHour());
                                    file.delete();
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("deleteJar() error",e);
        }
    }
}
